package com.hongmeng.teamwork.filter;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.hongmeng.teamwork.constants.HttpHeadConstant;
import com.hongmeng.teamwork.entity.base.Result;
import com.hongmeng.teamwork.utils.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Log4j2
@Component
public class AuthFilter extends OncePerRequestFilter {

    List<String> allowPostUri = Lists.newArrayList("/task/query");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (log.isInfoEnabled()) {
            log.info("request uri: {}, request method: {}", uri, request.getMethod());
        }
        if (uri.startsWith("/auth") ||
                request.getMethod().equalsIgnoreCase("GET") ||
                allowPostUri.contains(uri)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(HttpHeadConstant.ACCESS_TOKEN);
        if (StringUtils.isBlank(token)) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(Result.fail("token 不能为空")));
            writer.flush();
            writer.close();
            return;
        }
        filterChain.doFilter(request, response);
    }
}
